package com.ymatou.iapi.sellertrade.testcase;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.google.gson.Gson;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.req.ApplyRefundReq;
import com.ymatou.iapi.optrade.parameter.req.ChangeRefundBillReq;
import com.ymatou.iapi.optrade.parameter.req.DelayReceiveReq;
import com.ymatou.iapi.optrade.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.optrade.parameter.vo.OrderGroupVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderItemVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderVo;
import com.ymatou.iapi.optrade.parameter.vo.SalesRefundInfoVo;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.ChangeSalesRefundInfoCall;
import com.ymatou.iapi.optrade.service.DelayReceiveCall;
import com.ymatou.iapi.optrade.service.PrepaidCardService;
import com.ymatou.iapi.optrade.service.RefundService;
import com.ymatou.iapi.sellertrade.parameter.GetOrderListRequestJavaBean;
import com.ymatou.iapi.sellertrade.response.GetOrderListResponseJavaBean;
import com.ymatou.iapi.sellertrade.service.GetOrderListJavaCall;
import com.ymatou.iapi.sellertrading.parameter.GetOrderListRequestBean;
import com.ymatou.iapi.sellertrading.response.GetOrderListResponseBean;
import com.ymatou.iapi.sellertrading.service.GetOrderListCall;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.PayGateWayCallService;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceOrderCallService;
import com.ymttest.business.service.YMTTrading.TradingProductVo;
import com.ymttest.database.sharding.db.sharding.model.AutoReceiveOptPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.FileUtil;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.compare.AssertHelper;
import com.ymttest.utils.compare.LoggerHelper;

public class Ts_GetOrderListJava {
	
	//java接口
	private static GetOrderListRequestJavaBean getOrderListRequestJavaBean;
	private static GetOrderListJavaCall getOrderListJavaCall;
	
	//.net接口
	private static GetOrderListRequestBean getOrderListRequestBean;
	private static GetOrderListCall getOrderListCall;
	
	private static long userId = 20238699;
	
	private static Long sellerId = Long.valueOf(EnvSetup.getData("autotest_seller1"));
	private static String sellerName = String.valueOf(EnvSetup.getData("autotest_sellerName1"));

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("新买手交易服务java版本--获取订单列表");
	}

	@Before
	public void caseUp() {

		getOrderListRequestJavaBean = new GetOrderListRequestJavaBean();
		
		getOrderListRequestBean = new GetOrderListRequestBean();
		

	}
	@AfterClass
	public static void tearDown() {
		Logger.generateResult(getOrderListJavaCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	/**
	 * 创建一个已支付使用优惠券带有app内立减优惠的订单
	 * @return
	 */
	public long createOrder1() {

		TradingServiceResp placeOrder = TradingPlaceOrderCallService
				.placeOrderWithThreeProcutInTwoOrder(true, BigDecimal.TEN,
						userId, LogisticsTypeEnum.OVERSEAS_DELIVERY);

		long userId = placeOrder.getUserId();
		List<Order> orderList = placeOrder.getOrderList();
		long sellerId = orderList.get(0).getSellerId();
		long tradingId = placeOrder.getTradingId();
		long mainOrderId = placeOrder.getMainOrderId();

		TradingCallService.payOrder(userId, BigDecimal.TEN,
				tradingId, true);
		Logger.comment(String.valueOf(mainOrderId));
		for (int i = 0; i < orderList.size(); i++)
			TradingSyncService.getSyncResult(orderList.get(i).getOrderId());
		
		return sellerId;
	}
	
	/**
	 * 创建一个确认收货使用预付卡和优惠券的订单
	 * @return
	 */
	public void createOrder2() throws Exception {
		TradingServiceResp placeOrderResp = PrepaidCardService
				.placeOrder2(true);
		List<Order> orderList = placeOrderResp.getOrderList();
		long sellerId = orderList.get(0).getSellerId();
		Long userId = placeOrderResp.getUserId();
		
		BigDecimal totalPrice = placeOrderResp.getPayableAmount();

		// 用余额支付金额
		BigDecimal useAccountAmount = new BigDecimal(47);
		// 支付订单 余额+支付宝组合支付
		// 13 为 app国际支付宝，15 微信
		String payType = "13";

		Long thirdTradingId = TradingCallService.payOrder(
				placeOrderResp.getUserId(), useAccountAmount,
				placeOrderResp.getTradingId(), payType);

		// 支付网关支付回调交易
		PayGateWayCallService.notifyCall(payType,
				String.valueOf(thirdTradingId),
				totalPrice.subtract(useAccountAmount).toString(),
				userId.intValue());

		// 等待支付网关异步处理
		Thread.sleep(5000);
		
		for(int i = 0; i < orderList.size(); i++) {
			long orderId = orderList.get(i).getOrderId();
			// 卖家接单
			TradingCallService.sellerAcceptOrder(sellerId, orderId);
			//买家确认收货
			TradingCallService.confirmReceive(userId, orderId);
		}
	}
	
	/**
	 * 创建一个用户确认收货带延迟收货订单
	 * @return
	 */
	public void createOrder3() throws Exception {
		
		TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
				.placeOrderWithLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

		long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
		
		long userId = placeOrderResp.getUserId();

		long tradingId = placeOrderResp.getTradingId();

		BigDecimal useAccountAmount = placeOrderResp.getPayableAmount();

		TradingCallService.payOrder(userId, useAccountAmount, tradingId);

		TradingCallService.sellerAcceptOrder(sellerId, orderId);

		TradingCallService.delivery(sellerId, orderId,
				LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);

		// 自动确认收货时间操作表（auto_receive_opt）
		AutoReceiveOptPo record = new AutoReceiveOptPo();
		record.setOrderId(orderId);
		record.setExpectReceiveTime(DateTime.now().plusDays(-1).toDate());
		record.setFreeze(false);

		// 修改预期自动确认收货
		new OrderShardingWapper().autoReceiveOptMapper
				.updateByPrimaryKeySelective(record);

		int delayDay = new Random().nextInt(10) + 1;

		DelayReceiveReq delayReceiveReq = new DelayReceiveReq();
		DelayReceiveCall delayReceiveCall = new DelayReceiveCall();

		delayReceiveReq.setDelayDay(delayDay);
		delayReceiveReq.setOrderId(orderId);
		delayReceiveReq.setOperateUserId(userId);

		delayReceiveReq.setOperateUserType(0);
		// 发送请求
		delayReceiveCall.setData(false, delayReceiveReq);
		delayReceiveCall.callService();

		TradingCallService.confirmReceive(userId, orderId);
		TradingSyncService.getSyncResult(orderId);
	}
	
	/**
	 * 创建一个申请退款的订单
	 * @return
	 */
	public void createOrder4() throws Exception {
		
		TradingServiceResp placeOrder = TradingPlaceOrderCallService
				.placeOrderWithThreeProcutInTwoOrder(true, BigDecimal.TEN,
						userId, LogisticsTypeEnum.OVERSEAS_DELIVERY);

		long userId = placeOrder.getUserId();
		List<Order> orderList = placeOrder.getOrderList();
		long sellerId = orderList.get(0).getSellerId();
		long tradingId = placeOrder.getTradingId();

		TradingCallService
				.payOrder(userId, BigDecimal.TEN, tradingId, true);

		for (int i = 0; i < orderList.size(); i++) {
			TradingCallService.sellerAcceptOrder(sellerId, orderList.get(i)
					.getOrderId());
			RefundService.applyRefund(orderList.get(i));
			TradingSyncService.getSyncResult(orderList.get(i).getOrderId());
		}
	}
	
	/**
	 * 创建一个修改退款申请并最后拒绝退款的订单
	 * @return
	 */
	public void createOrder5() throws Exception {
		
		TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
				.placeOrderWithThreeProcutInTwoOrder(true, BigDecimal.ZERO,
						userId, LogisticsTypeEnum.OVERSEAS_DELIVERY);

		Order order = placeOrderResp.getOrderList().get(0);
		Long orderId = order.getOrderId();

		BigDecimal orderFreight = order.getOrderFreight();

		BigDecimal proFreight = order.getOrderDetailPoList().get(0)
				.getFreight();

		// 支付
		TradingCallService.payOrder(placeOrderResp.getUserId(),
				placeOrderResp.getPayableAmount(),
				placeOrderResp.getTradingId());
		// 接单
		TradingCallService.sellerAcceptOrder(order.getSellerId(), orderId);

		// 申请改订单下第一个商品退款
		ApplyRefundReq applyRefundReq = RefundService
				.buildStandApplyRefundReq(order);

		SalesRefundInfoVo oldRefundInfoVo = applyRefundReq
				.getSalesRefundInfoList().get(0);

		applyRefundReq.setSalesRefundInfoList(Arrays
				.asList(oldRefundInfoVo));

		RefundService.applyRefundCall(applyRefundReq);

		ChangeRefundBillReq changeRefundBillReq = new ChangeRefundBillReq();

		ChangeSalesRefundInfoCall changeSalesRefundInfoCall = new ChangeSalesRefundInfoCall();

		changeRefundBillReq.setOrderId(orderId);
		changeRefundBillReq.setRefundBillNo(oldRefundInfoVo
				.getRefundBillNo());

		changeRefundBillReq.setRefundAmount(oldRefundInfoVo
				.getRefundAmount().add(orderFreight.subtract(proFreight)));

		changeRefundBillReq.setRefundProductNum(oldRefundInfoVo
				.getRefundProductNum());

		changeRefundBillReq.setRefundType(1);
		changeRefundBillReq.setReason("123456789");

		changeSalesRefundInfoCall.setData(false, changeRefundBillReq);
		changeSalesRefundInfoCall.callService();

		RefundService.rejectRefundCall(applyRefundReq);
	}
	
	/**
	 * 创建一个全部退款成功的订单
	 * @return
	 */
	public void createOrder6() throws Exception {
		
		Logger.comment("前置数据准备");

		TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
				.placeOrderWithThreeProcutInTwoOrder(true, BigDecimal.ZERO,
						userId, LogisticsTypeEnum.OVERSEAS_DELIVERY);

		Order order = placeOrderResp.getOrderList().get(0);

		Long userId = placeOrderResp.getUserId();
		Long orderId = order.getOrderId();

		long sellerId = order.getSellerId();

		// 支付
		TradingCallService.payOrder(placeOrderResp.getUserId(),
				placeOrderResp.getPayableAmount(),
				placeOrderResp.getTradingId());
		// 接单
		TradingCallService.sellerAcceptOrder(order.getSellerId(), orderId);

		// 退款
		RefundService.applyRefund(order);

		RefundService.approveRefund(order);

		TradingSyncService.getSyncResult(orderId);

		TradingSyncService.verify(orderId, userId, sellerId);
	}
	
	/**
	 * 创建组合商品下单，调整运费，折扣，使用招行折扣支付的订单
	 * @return
	 */
	public void createOrder7() throws Exception {

		TradingServiceResp placeOrder = TradingPlaceOrderCallService
				.placeOrderWithThreeProcutInTwoOrder(true, BigDecimal.ZERO,
						userId, LogisticsTypeEnum.OVERSEAS_DELIVERY);

		Long userId = placeOrder.getUserId();
		long sellerId = placeOrder.getOrderList().get(0).getSellerId();
		long orderId = placeOrder.getOrderList().get(0).getOrderId();

		BigDecimal totalPrice = placeOrder.getPayableAmount();
		long tradingId = placeOrder.getTradingId();

		// 调整订单折扣
		YmatouEasyCall YmatouEasyCall = new YmatouEasyCall("", "POST",
				"JSON");
		String orderJson = "{\"OrderId\":" + orderId + ",\"SellerId\":"
				+ sellerId
				+ ",\"Discount\":28,\"Freight\":35,\"DiscountTime\":\""
				+ YMTDateUtil.getSysTime() + "\"}";
		YmatouEasyCall
				.setUrl("http://optrade.iapi.ymatou.com/api/Seller/ChangeOrderDiscount");
		YmatouEasyCall.setData(orderJson);
		YmatouEasyCall.callService();

		// 获取用户需要支付的金额
		String payType = "50";
		Long thirdTradingId = TradingCallService.payOrder(userId,
				BigDecimal.ZERO, tradingId, payType);

		// 支付网关支付回调交易
		PayGateWayCallService.cmbNotifyCall(thirdTradingId.toString(),
				totalPrice.subtract(BigDecimal.ZERO).toString(),
				userId.intValue(), BigDecimal.TEN.toString());
	}
	
	/**
	 * 创建预售订单
	 * @return
	 */
	public void createOrder8() throws Exception {
		
		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq();
		
		OrderGroupVo orderGroupVo = TradingCallService.createOrderGroupVo(sellerId, sellerName);
		OrderVo orderVo = TradingCallService.createOrderVo();
		
		// 创建一个普通商品
		TradingProductVo productVo = TradingProductVo.createPro(sellerId,
				sellerName, 5);

		OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
				productVo.getProductId(), productVo.getCatalogId());
		orderItemVo.setPreSale(true);
		
		orderVo.setOrderItems(Arrays.asList(orderItemVo));
		orderGroupVo.setOrders(Arrays.asList(orderVo));
		placeOrderReq.setOrderGroups(Arrays.asList(orderGroupVo));		

		TradingCallService
				.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 创建使用了预付卡订单,退款后订单
	 * @return
	 */
	public void createOrder9() throws Exception {
		
		TradingServiceResp placeOrderResp = PrepaidCardService
				.placeOrder2(true);

		Order order = placeOrderResp.getOrderList().get(0);
		long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
		long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();
		Long userId = placeOrderResp.getUserId();

		BigDecimal totalPrice = placeOrderResp.getPayableAmount();

		// 用余额支付金额
		BigDecimal useAccountAmount = new BigDecimal(47);
		// 支付订单 余额+支付宝组合支付
		// 13 为 app国际支付宝，15 微信
		String payType = "13";

		Long thirdTradingId = TradingCallService.payOrder(
				placeOrderResp.getUserId(), useAccountAmount,
				placeOrderResp.getTradingId(), payType);

		// 支付网关支付回调交易
		PayGateWayCallService.notifyCall(payType,
				String.valueOf(thirdTradingId),
				totalPrice.subtract(useAccountAmount).toString(),
				userId.intValue());
		TradingCallService.sellerAcceptOrder(sellerId, orderId);
		RefundService.approveRefund(order);
	}
	
	/**
	 * 创建含有平台优惠商品订单
	 * @return
	 */
	public void createOrder10() throws Exception {
		
		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq();
		
		OrderGroupVo orderGroupVo = TradingCallService.createOrderGroupVo(sellerId, sellerName);
		OrderVo orderVo = TradingCallService.createOrderVo();
		
		// 创建一个普通商品
		TradingProductVo productVo = TradingProductVo.createPro(sellerId,
				sellerName, 5);

		OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
				productVo.getProductId(), productVo.getCatalogId());
		orderItemVo.setYmtPromotionAmount(BigDecimal.TEN);
		
		orderVo.setOrderItems(Arrays.asList(orderItemVo));
		orderGroupVo.setOrders(Arrays.asList(orderVo));
		placeOrderReq.setOrderGroups(Arrays.asList(orderGroupVo));		

		TradingCallService
				.callPlaceOrderService(placeOrderReq);
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetOrderListJava_001() {
		Logger.start(true,"GetOrderList新老接口对比");
		try {
			String startTime = YMTDateUtil.getSysTime();
			Logger.comment("前置数据准备");

			long sellerId = this.createOrder1();
			this.createOrder2();
			this.createOrder3();
			this.createOrder4();
			this.createOrder5();
			this.createOrder6();
			this.createOrder7();
			this.createOrder8();
			this.createOrder9();
			this.createOrder10();
			
			Logger.comment("前置数据准备结束");
		
			//java接口request
			getOrderListRequestJavaBean.setTradingStatus(0);
			getOrderListRequestJavaBean.setStartTime(startTime);
			getOrderListRequestJavaBean.setEndTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
			getOrderListRequestJavaBean.setOvertimeType(0);
			getOrderListRequestJavaBean.setPage(1);
			getOrderListRequestJavaBean.setPageSize(20);
			getOrderListRequestJavaBean.setPackageDelivery(0);
			//getOrderListRequestJavaBean.setMasterOrderId(mainOrderId);
			//getOrderListRequestJavaBean.setMasterOrderId(Long.valueOf(1858068699));
			
			//.net接口request
			getOrderListRequestBean.setTradingStatus(0);
			getOrderListRequestBean.setStartTime(startTime);
			getOrderListRequestBean.setEndTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
			getOrderListRequestBean.setOvertimeType(0);
			getOrderListRequestBean.setPage(1);
			getOrderListRequestBean.setPageSize(20);
			getOrderListRequestBean.setPackageDelivery(0);
			//getOrderListRequestBean.setMasterOrderId(mainOrderId);
			//getOrderListRequestBean.setMasterOrderId(Long.valueOf(1858068699));
			
			getOrderListJavaCall = new GetOrderListJavaCall(sellerId);
			getOrderListCall = new GetOrderListCall(sellerId, sellerId);
			//java返回值
			String json_java = getOrderListJavaCall.callAndGetReturnData(getOrderListRequestJavaBean).toString();
			GetOrderListResponseJavaBean response_java = new Gson().fromJson(json_java, 
					GetOrderListResponseJavaBean.class);
			
			//.net返回值
			String json_net = getOrderListCall.callAndGetReturnData(getOrderListRequestBean).toString();
			GetOrderListResponseBean response_net = new Gson().fromJson(json_net, 
					GetOrderListResponseBean.class);
			
			AssertHelper.setLoggerInterface(new LoggerHelper());
			AssertHelper.assertResultEqual(response_net, response_java, "GetOrderList接口对比");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetOrderListJava_002() {
		Logger.start(true,"STG接口-GetOrderList新老接口对比");
		try {
			String dd = "D:\\在测项目\\sellerId.txt";
			List<String> sellerIds = FileUtil.readFileAsLine(dd);
			
			for (int i = 0; i < sellerIds.size(); i++) {
				//java接口request
				getOrderListRequestJavaBean.setTradingStatus(0);
				getOrderListRequestJavaBean.setStartTime("2018-08-01 00:00:00");
				getOrderListRequestJavaBean.setEndTime("2018-09-01 23:59:59");
				getOrderListRequestJavaBean.setOvertimeType(0);
				getOrderListRequestJavaBean.setPage(1);
				getOrderListRequestJavaBean.setPageSize(20);
				getOrderListRequestJavaBean.setPackageDelivery(0);
				
				//.net接口request
				getOrderListRequestBean.setTradingStatus(0);
				getOrderListRequestBean.setStartTime("2018-08-01 00:00:00");
				getOrderListRequestBean.setEndTime("2018-09-01 23:59:59");
				getOrderListRequestBean.setOvertimeType(0);
				getOrderListRequestBean.setPage(1);
				getOrderListRequestBean.setPageSize(20);
				getOrderListRequestBean.setPackageDelivery(0);
				
				getOrderListJavaCall = new GetOrderListJavaCall(Long.valueOf(sellerIds.get(i)));
				getOrderListCall = new GetOrderListCall(Long.valueOf(sellerIds.get(i)), Long.valueOf(sellerIds.get(i)));
				//java返回值
				String json_java = getOrderListJavaCall.callAndGetReturnData(getOrderListRequestJavaBean).toString();
				GetOrderListResponseJavaBean response_java = new Gson().fromJson(json_java, 
						GetOrderListResponseJavaBean.class);
				
				//.net返回值
				String json_net = getOrderListCall.callAndGetReturnData(getOrderListRequestBean).toString();
				GetOrderListResponseBean response_net = new Gson().fromJson(json_net, 
						GetOrderListResponseBean.class);
				
				AssertHelper.setLoggerInterface(new LoggerHelper());
				AssertHelper.assertResultEqual(response_net, response_java, "GetOrderList接口对比");
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}
